/**
 * MethodSelectorView.js
 *
 * 负责展示方法下拉列表以及已选方法标签。
 * 提供 API 供外部获取/清空选中方法，并在打开下拉列表时请求后端数据。
 */
(function() {
    'use strict';

    class MethodSelectorView {
        constructor(options = {}) {
            this.onRequestMethods = options.onRequestMethods;
            this.onSelectionChange = options.onSelectionChange;
            this.methods = [];
            this.selectedMethods = [];

            this.dropdownButton = document.getElementById('method-dropdown-button');
            this.dropdown = document.getElementById('method-dropdown');
            this.selectedArea = document.getElementById('selected-methods-area');
            this.selectedList = document.getElementById('selected-methods-list');

            this._bindEvents();
        }

        _bindEvents() {
            if (this.dropdownButton) {
                this.dropdownButton.addEventListener('click', (event) => {
                    event.stopPropagation();
                    this.toggleDropdown();
                    if (this.methods.length === 0 && typeof this.onRequestMethods === 'function') {
                        this.onRequestMethods();
                    }
                });
            }

            document.addEventListener('click', (event) => {
                const target = event.target;
                if (!(target instanceof Element)) {
                    this.closeDropdown();
                    return;
                }
                if (!target.closest('#method-selector')) {
                    this.closeDropdown();
                }
            });
        }

        toggleDropdown() {
            if (!this.dropdown) {
                return;
            }
            this.dropdown.classList.toggle('show');
        }

        closeDropdown() {
            if (this.dropdown) {
                this.dropdown.classList.remove('show');
            }
        }

        setMethods(methods) {
            this.methods = methods || [];
            if (this.selectedMethods.length) {
                const validIds = new Set(this.methods.map(method => method.id));
                const originalLength = this.selectedMethods.length;
                this.selectedMethods = this.selectedMethods.filter(method => validIds.has(method.id));
                if (this.selectedMethods.length !== originalLength) {
                    this._renderSelected();
                    this.onSelectionChange?.(this.getSelectedMethodIds());
                }
            }
            this._renderDropdown();
        }

        _renderDropdown() {
            if (!this.dropdown) {
                return;
            }
            if (!this.methods.length) {
                this.dropdown.innerHTML = '<p class="method-dropdown-empty">暂无可用方法</p>';
                return;
            }

            const listHtml = this.methods.map(method => {
                const metaParts = [];
                if (method.className) {
                    metaParts.push(method.className);
                }
                if (method.packageName) {
                    metaParts.push(method.packageName);
                }
                const meta = metaParts.join(' · ');
                return `
                    <div class="method-option" data-id="${method.id}">
                        <div class="method-option-name">${method.name || 'Untitled'}</div>
                        <div class="method-option-meta">${meta}</div>
                    </div>
                `;
            }).join('');

            this.dropdown.innerHTML = listHtml;
            this.dropdown.querySelectorAll('.method-option').forEach(option => {
                option.addEventListener('click', () => {
                    const id = Number(option.getAttribute('data-id'));
                    this._selectMethod(id);
                });
            });
        }

        _selectMethod(id) {
            if (this.selectedMethods.some(method => method.id === id)) {
                this.closeDropdown();
                return;
            }
            const method = this.methods.find(m => m.id === id);
            if (method) {
                this.selectedMethods.push(method);
                this._renderSelected();
                this.onSelectionChange?.(this.getSelectedMethodIds());
            }
            this.closeDropdown();
        }

        _renderSelected() {
            if (!this.selectedList || !this.selectedArea) {
                return;
            }
            this.selectedArea.style.display = this.selectedMethods.length ? 'block' : 'none';
            this.selectedList.innerHTML = '';

            this.selectedMethods.forEach((method, index) => {
                const item = document.createElement('div');
                item.className = 'attachment-item';
                item.title = `${method.className}.${method.name}`;
                item.innerHTML = `
                    <span class="codicon codicon-symbol-method"></span>
                    <span class="attachment-name">${method.name}</span>
                    <span class="codicon codicon-close attachment-remove"></span>
                `;
                const removeBtn = item.querySelector('.attachment-remove');
                if (removeBtn) {
                    removeBtn.addEventListener('click', (event) => {
                        event.stopPropagation();
                        this.selectedMethods.splice(index, 1);
                        this._renderSelected();
                        this.onSelectionChange?.(this.getSelectedMethodIds());
                    });
                }
                this.selectedList.appendChild(item);
            });
        }

        getSelectedMethodIds() {
            return this.selectedMethods.map(method => method.id);
        }

        getSelectedMethods() {
            return [...this.selectedMethods];
        }

        clearSelection() {
            this.selectedMethods = [];
            this._renderSelected();
            this.onSelectionChange?.([]);
        }
    }

    window.MethodSelectorView = MethodSelectorView;
})();
